﻿using Microsoft.Extensions.Logging;
using ShanNiang.Hosting;
using ShanNiang.Service.Interfaces;
using ShanNiang.Service.Scaner;

namespace ShanNiang.Service.Implementations
{
    public class ScanerService : LocalService, IScanerService
    {
        private readonly ScanerListener _scanerListener;

        public event EventHandler<CodeEventArgs>? CodeScaned;


        public ScanerService(ILogger<LocalService> logger) : base(logger)
        {
            _scanerListener = new ScanerListener();
        }

        public void Start()
        {
            _scanerListener.ScanerEvent += ScanerListener_ScanerEvent    ;
            _scanerListener.Start();
            Logger.LogDebug("The scanner starts listening");
        }

        private void ScanerListener_ScanerEvent(object? sender, ScanerEventArgs e)
        {
            var args = new CodeEventArgs(e.ScannedText);
            Logger.LogDebug("The text has been scanned :[{0}], CodeType is {1}, Code is {2}", args.ScannedText, args.CodeType, args.Code);
            CodeScaned?.Invoke(this, args);
        }

        public void Stop()
        {
            _scanerListener.ScanerEvent -= ScanerListener_ScanerEvent;
            _scanerListener.Stop();
            Logger.LogDebug("The scanner stops listening");
        }
    }
}
